'''
作者：刘宇轩
文件名称：仿射加密
时间：2021.3.23
'''

import tkinter as tk
from tkinter import ttk

win = tk.Tk()
win.title("仿射加密")


def encrypt():  # 加密
    x = e.get()
    en1 = []
    de1 = []
    for i in range(len(x)):
        if ord(x[i]) >= 97:
            en1.append(chr(((ord(x[i]) - 97) * 5 + 8) % 26 + 65))
        if 97 > ord(x[i]) >= 65:
            en1.append(chr(((ord(x[i]) - 65) * 5 + 8) % 26 + 97))
        '''if 47 < x[i] < 58:
            en1.append()'''
    en2 = ''.join(en1)
    for i in range(len(en2)):
        if ord(en2[i]) >= 97:
            de1.append(chr((((ord(en2[i]) - 97) - 8) * 21) % 26 + 65))
        if 97 > ord(en2[i]) >= 65:
            de1.append(chr((((ord(en2[i]) - 65) - 8) * 21) % 26 + 97))
    de2 = ''.join(de1)
    b.configure(text="密文： " + en2 + "加密验证：" + de2)


def decode1():  # 解密
    y = d.get()
    de = []
    for i in range(len(y)):
        if ord(y[i]) >= 97:
            de.append(chr((((ord(y[i]) - 97) - 8) * 21) % 26 + 65))
        if 97 > ord(y[i]) >= 65:
            de.append(chr((((ord(y[i]) - 65) - 8) * 21) % 26 + 97))
    de3 = ''.join(de)
    b2.configure(text="明文： " + de3)


l = ttk.Label(win, text='字母加密\n加密函数：E(x) = (5x + 8) (mod 26)\n解密函数：D(x) = 21(x - 8) (mod 26)').grid(column=0, row=0)
# 加密部分
l1 = ttk.Label(win, text='输入明文').grid(column=0, row=1)
e = tk.StringVar()
e_entered = ttk.Entry(win, width=12, textvariable=e)
e_entered.grid(column=1, row=1)
b = ttk.Button(win, text="加密", command=encrypt)
b.grid(column=2, row=1)

# 解密部分
l2 = ttk.Label(win, text='输入密文').grid(column=0, row=2)
d = tk.StringVar()
d_entered = ttk.Entry(win, width=12, textvariable=d)
d_entered.grid(column=1, row=2)
b2 = ttk.Button(win, text="解密", command=decode1)
b2.grid(column=2, row=2)
win.mainloop()